<template>
  <div class="course-management" style="display: flex; flex-direction: column; justify-content: center;">
    <!-- 顶部标题 -->
    <div class="operation-bar">
      <div style="width: 420px; border-bottom: 2px solid rgb(36, 67, 130); margin-bottom: 15px;">
        <p class="cousename">{{ courseName }}</p>
      </div>
    </div>

    <!-- 主体布局 -->
    <div class="main-layout">
      <!-- 左侧章节树 -->
      <div class="left-tree">
        <el-tree
          :data="chapters"
          node-key="id"
          default-expand-all
          @node-click="handleNodeClick"
          style="font-size: 16px;"
          :expand-on-click-node="false"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <el-icon v-if="data.type === 'chapter'"><FolderOpened /></el-icon>
              <el-icon v-else><Files /></el-icon>
               <span>{{ short(node.label) }}</span>
              <span v-if="data.type === 'section'" class="progress-solid" :style="getProgressStyle(data.progress)">
              </span>
            </span>
          </template>
        </el-tree>
      </div>

      <!-- 右侧资源管理 -->
      <div class="right-content">
        <div v-if="selectedSection" style="margin-top: -20px;">
          <h3 class="section-title">{{ selectedSection.label }}</h3>

          <!-- 资源类型导航 -->
          <div class="resource-types">
            <el-button
              v-for="type in resourceTypes"
              :key="type.value"
              :type="activeType === type.value ? 'primary' : ''"
              @click="activeType = type.value"
            >
              <el-icon :size="16"><component :is="type.icon" /></el-icon>
              {{ type.label }}
            </el-button>
          </div>

          <!-- 资源列表 -->
          <div class="resource-list">
            <template v-if="filteredResources.length">
              <div v-for="resource in filteredResources" :key="resource.id" class="resource-item">
                              <!-- 完成状态小圆点 -->
                  <div class="status-dot" :class="{ completed: resource.isWatched }">
                    <span v-if="resource.isWatched" class="check-mark">✔</span>
                  </div>
                <div class="resource-left" @click="handlePreview(resource)">
                  <!-- 视频 -->
                  <div v-if="resource.type === 'video'" class="video-container">
                    <img :src="resource.cover" class="video-cover" />
                    <div class="play-button">
                      <el-icon size="30"><VideoPlay /></el-icon>
                    </div>
                  </div>

                  <!-- 图片 -->
                  <div v-else-if="resource.type === 'image'" class="image-container">
                    <img :src="resource.cover" class="image-cover" />
                  </div>

                  <!-- 文档 / PPT -->
                  <div v-else class="file-icon">
                    <el-icon :size="40">
                      <component :is="resource.type === 'document' ? Document : Files" />
                    </el-icon>
                  </div>
                </div>

                <div class="resource-center" @click="handlePreview(resource)">
                  <div class="resource-name">{{ resource.name }}</div>
                  <div class="upload-time">上传时间：{{ resource.uploadTime }}</div>
                </div>

                <div class="resource-right">
                   <el-button size="mini" @click="handlePreview(resource)">查看</el-button>

                  <!-- 收藏星星按钮 -->
                  <div class="favorite-icon" @click.stop="toggleFavorite(resource)">
                    <img 
                      :src="resource.isStared ? require('@/assets/picture/star-solid.png') : require('@/assets/picture/star.png')" 
                      :alt="resource.isFavorite ? '已收藏' : '未收藏'"
                    />
                  </div>
                </div>

              </div>
            </template>

            <div v-else class="empty-resource">
              <el-empty description="暂无资源" />
            </div>
          </div>


        </div>
      </div>
    </div>
  </div>
</template>
<script setup>import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { FolderOpened, Files, Document, VideoPlay } from '@element-plus/icons-vue'
import { fetchStudentChapters, StufetchStudentResources, StufetchClassDetails, addStudentFavorite, removeStudentFavorites } from '@/services/api'

const router = useRouter()
const userId = ref(localStorage.getItem('id'))
const courseName = ref('')
const chapters = ref([])
const selectedSection = ref(null)
const activeType = ref('document')

const resourceTypes = ref([
  { value: 'document', label: '文档', icon: Document },
  { value: 'ppt', label: 'PPT', icon: Files },
  { value: 'video', label: '视频', icon: FolderOpened },
  { value: 'image', label: '图片', icon: FolderOpened }
])

onMounted(async () => {
  await loadCourseName()
  await loadChapters()
})
const short = (txt, n = 15) =>  // 从18改为15
  txt.length > n ? txt.slice(0, n) + '…' : txt;
const loadCourseName = async () => {
  try {
    const res = await StufetchClassDetails(localStorage.getItem('selectedClassId'), userId.value)
    if (res.data.status === 1) {
      courseName.value = res.data.data.semester_name
    }
  } catch (error) {
    console.error('加载课程失败', error)
  }
}

const loadChapters = async () => {
  try {
    const res = await fetchStudentChapters(localStorage.getItem('selectedClassId'), userId.value)
    chapters.value = transformChapterData(res.data.data)
  } catch (error) {
    console.error('加载章节失败', error)
  }
}

const transformChapterData = (apiData) => {
  return apiData.map(chapter => ({
    id: chapter.unit_id,
    label: chapter.unit_title,
    type: 'chapter',
    children: chapter.children?.map(section => ({
      id: section.unit_id,
      label: section.unit_title,
      type: 'section',
      progress: section.unit_progress
    })) || []
  }))
}

const handleNodeClick = async (data) => {
  if (data.type === 'section') {
    try {
      const res = await StufetchStudentResources(data.id, userId.value)
      data.resources = transformResourceData(res.data.data)
      selectedSection.value = data
    } catch (error) {
      console.error('加载资源失败', error)
    }
  }
}

const transformResourceData = (apiData) => {
  return apiData.map(item => ({
    id: item.unit_re_id,
    name: item.resource.resource_name,
    type: item.resource.resource_type === 'word' ? 'document' : 
          item.resource.resource_type === 'pic' ? 'image' : 
          item.resource.resource_type.toLowerCase(),
    uploadTime: item.create_time,
    cover: item.video_cover || (item.resource.resource_type === 'pic' ? item.resource.resource_url : ''),
    url: item.resource.resource_url,
    isWatched: item.isWatched,
    isStared: item.isStared,
    resource_id: item.resource.resource_id,
    re_star_id: item.re_star_id,
    unit_re_id: item.unit_re_id
  }))
}

const filteredResources = computed(() => {
  return selectedSection.value?.resources?.filter(r => r.type === activeType.value) || []
})

const handlePreview = (resource) => {
  router.push({
    path: 'StuResourceViewer',
    query: {
      type: resource.type,
      url: resource.url,
      name: resource.name,
      uploadTime: resource.uploadTime,
      unit_re_id: resource.unit_re_id,
      user_id: userId.value,
      unit_id: selectedSection.value.id,
    }
  })
}

const toggleFavorite = async (resource) => {
  if (resource.isStared) {
    try {
      const res = await removeStudentFavorites(resource.re_star_id)
      if (res.data.status === 1) {
        resource.isStared = false
        resource.re_star_id = null
        ElMessage.success('取消收藏成功')
      } else {
        ElMessage.error('取消收藏失败')
      }
    } catch (error) {
      console.error('取消收藏异常:', error)
      ElMessage.error('网络异常，取消失败')
    }
  } else {
    try {
      const res = await addStudentFavorite({
        user_id: userId.value,
        resource_id: resource.resource_id
      })
      if (res.data.status === 1) {
        resource.isStared = true
        resource.re_star_id = res.data.data?.re_star_id || null
        ElMessage.success('收藏成功')
      } else {
        ElMessage.error('收藏失败')
      }
    } catch (error) {
      console.error('收藏异常:', error)
      ElMessage.error('网络异常，收藏失败')
    }
  }
}

const getProgressStyle = (progress) => {
  const percentage = Math.floor(progress * 100)
  return {
    background: `conic-gradient(#409EFF ${percentage}%, #eee ${percentage}% 100%)`
  }
}

</script>
<style scoped>
.cousename {
  font-weight: bold;
  color: rgb(36, 67, 130);
  font-size: 18px;
}

.operation-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.main-layout {
  display: flex;
  gap: 20px;
  min-height: 450px;
}

.left-tree {
  width: 400px;
  border-right: 1px solid #eee;
  padding-right: 20px;
  max-height: 400px;
  overflow-y: auto;
}

.right-content {
  flex: 1;
  padding: 20px;
  margin-top: -70px;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-circle {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  border: 2px solid #ccc;
  margin-left: 8px;
}
.progress-circle.completed {
  background-color: #409EFF;
  border: 2px solid #409EFF;
}

.section-title {
  margin-bottom: 20px;
  font-size: 18px;
  color: #333;
}

.resource-types {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.resource-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}


.resource-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f9f9f9;
  padding: 10px;
  border-radius: 6px;
  transition: background 0.3s;
}

.resource-item:hover {
  background-color: #eef7ff;
}

.resource-left {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.video-container {
  width: 130px;
  }
.video-container, .image-container {
  position: relative;
  overflow: hidden;
  border-radius: 6px;
}
 .image-container {
  width: 60px;
  }
.video-cover {
  width: 100%;
  aspect-ratio: 4 / 3; /* 4:3 横向比例 */
  object-fit: cover;
}
.image-cover {
  width: 100%;
  aspect-ratio: 3 / 4; /* 3:4 竖向比例 */
  object-fit: cover;
}

.file-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}


.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: 0.3s;
}

.video-container:hover .play-button {
  opacity: 1;
}
.resource-center {
  flex: 1;
  margin-left: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  cursor: pointer;
}

.resource-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.upload-time {
  margin-top: 6px;
  font-size: 12px;
  color: #999;
}

.resource-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.empty-resource {
  margin-top: 50px;
}

.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
.progress-solid {
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-left: 8px;
  border-radius: 50%;
  background: #eee; /* 默认灰色 */
  transition: background 0.5s ease;
  position: absolute;
  right: 10px;
}
.resource-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.resource-actions {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.status-dot {
  top: 8px;
  left: 8px;
  width: 13px;
  height: 13px;
  border-radius: 50%;
  background-color:  gray; /* 默认灰色 */
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: white;
  font-weight: bold;
  z-index: 10;

  margin-right: 8px;
}

.status-dot.completed {
  background-color:#67C23A; /* 绿色完成 */
}

.check-mark {
  font-size: 10px;
}

.favorite-icon {
  border-radius: 50%;
  padding: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.favorite-icon img {
  width: 24px;
  height: 24px;
}
.left-tree :deep(.el-tree-node__content) {
  min-height: 40px;  /* 将节点高度从默认的26px增加到40px */
  margin:  0;     /* 添加上下边距 */
}
</style>
